<script lang="ts" setup>
import { computed, onMounted, ref } from 'vue';
import { message } from 'ant-design-vue';
import { api } from '@/api/api'; // 确保导入了 API 模块
import { useLevelStore } from '@/stores/TeacherLevel';
import { InfoCircleOutlined } from '@ant-design/icons-vue';
// import logo from '@/assets/004.png'

import { getIcon } from "@/api/assets/assets";
import { useResourceStore } from '@/stores/TeacherResource';

// Props定义
const props = defineProps<{
  visible: boolean;
  onClose: () => void;
  courseFileId: string;
  courseId: string;
  sortId: string | number;
  fetchCourseData: (courseFileId: string | null, load: boolean, searchValue: string) => Promise<void>;
}>();

const logo = ref<string | undefined>(undefined);

const fetchIcon = async () => {
  try {
    const data = await getIcon(['004.png']);
    logo.value = data['004.png'];
  }
  catch (error) {
    console.error('API 调用错误:', error);
  }
};

onMounted(() => {
  fetchIcon();
});

// 初始化数据
const language = ref<string>('中文');
const isVisable = ref<boolean>(false);
const isTranslated = ref<boolean>(false);
const speakerType = ref<string>('暂不体验');
const fileList = ref<any[]>([]);
const uploadProgress = ref<number>(0);

// 获取语言代码
const getLanguageCode = (language: string): string => {
  switch (language) {
    case '中文':
      return 'cn';
    case '英语':
      return 'en';
    case '日语':
      return 'ja';
    case '韩语':
      return 'ko';
    default:
      return 'cn'; // 默认值
  }
};

// 重置表单数据
const resetForm = () => {
  language.value = '中文';
  isTranslated.value = false;
  speakerType.value = '暂不体验';
  fileList.value = [];
};

// 上传开始处理函数
const handleStart = async () => {
  props.onClose();
  if (fileList.value.length === 0) {
    message.error('请先选择文件');
    return;
  }

  try {
    isVisable.value = true;
    const formData = new FormData();
    formData.append('file', fileList.value[0].originFileObj); // 添加文件到 FormData
    const languageCode = getLanguageCode(language.value);

    // 发送请求到指定接口
    await api.post('/java/teacher/handlefileSource/handlevideoSource_thread', formData, {
      params: {
        courseFileId: props.courseFileId,
        language: languageCode,
        isTranslated: isTranslated.value,
        speakerType: speakerType.value,
        courseId: props.courseId,
        sortOrder: props.sortId || 0,
      },
      onUploadProgress: (progressEvent: any) => {
        const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
        uploadProgress.value = percentCompleted; // 更新上传进度
      },
      timeout: 1000000,
    });
    message.success('文件上传成功');
    isVisable.value = false;
    await props.fetchCourseData(props.courseFileId, true, '');
    fileList.value = []; // 清除文件列表
  }
  catch (error) {
    message.error('文件加工失败，请重试');
    isVisable.value = false;
  }
  finally {
    resetForm();
  }
};

// 上传相关属性
const uploadProps = {
  multiple: false,
  beforeUpload: (file: any) => {
    fileList.value = [file]; // 只保留一个文件
    return false; // 阻止自动上传
  },
  onChange: ({ fileList: newFileList }: { fileList: any[] }) => {
    fileList.value = newFileList; // 更新文件列表
  },
  onRemove: (file: any) => {
    fileList.value = fileList.value.filter((item: any) => item.uid !== file.uid); // 过滤掉要删除的文件
  },
  action: '', // 确保不会自动触发上传
};

// 按钮样式
const getButtonStyle = (currentValue: string, selectedValue: string) => ({
  backgroundColor: currentValue === selectedValue ? '#1890ff' : '#f0f0f0', // 选中态为蓝色背景
  color: currentValue === selectedValue ? '#fff' : '#000', // 选中态文字为白色
  borderRadius: '0.56rem',
  width: '5.63rem',
});
</script>

<template>
  <a-modal
    :open="props.visible"
    :footer="null"
    width="50rem"
    @cancel="props.onClose"
  >
    <div class="modal-content">
      <div style="text-align: left; margin-bottom: 1rem">
        <h2 class="modal-title" style="font-size: 1.125rem; font-weight: normal;margin-bottom: 1.25rem ">
          上传本地音视频文件
        </h2>
      </div>
      <div class="modal-body">
        <div style="padding-right: 1.25rem; width: 21.875rem;">
          <a-upload-dragger
            :file-list="fileList"
            :before-upload="uploadProps.beforeUpload"
            :on-change="uploadProps.onChange"
            :on-remove="uploadProps.onRemove"
            action=""
            name="files"
            class="upload-dragger"
          >
            <div class="upload-icon-wrapper">
              <img :src="logo" alt="上传图标" class="upload-icon">
            </div>
            <p class="upload-text">
              点击 / 拖拽 本地音视频文件到这里
            </p>
            <ul style="margin-left: -1.125rem;margin-top: 0; font-size: 0.6875rem;">
              <li style="margin-bottom: 0.625rem; word-wrap: break-word; margin-left: 0;text-align: left;">
                单个文件最长6小时。
              </li>
              <li style="margin-bottom: 0.625rem;word-wrap: break-word;text-align: left;">
                视频支持mp4/wmv/m4v/flv/rmvb/dat/mov/mkv/webm/avi /mpeg/3gp/，单个最大6G；
              </li>
              <li style="margin-bottom: 0.625rem; word-wrap: break-word;text-align: left;">
                音频支持：mp3/wav/m4a/wma/aac/ogg/amr/flac/aiff，单个最大500M。
              </li>
            </ul>
          </a-upload-dragger>
        </div>
        <div class="settings-section">
          <div class="setting-item">
            <div class="setting-label">
              音视频语言
              <InfoCircleOutlined class="info-icon" />
            </div>
            <div class="button-group">
              <a-button :style="getButtonStyle('中文', language)" @click="language = '中文'">
                中文
              </a-button>
              <a-button :style="getButtonStyle('英语', language)" @click="language = '英语'">
                英语
              </a-button>
              <a-button :style="getButtonStyle('日语', language)" @click="language = '日语'">
                日语
              </a-button>
              <a-button :style="getButtonStyle('韩语', language)" @click="language = '韩语'">
                韩语
              </a-button>
            </div>
          </div>
          <div class="setting-item">
            <div class="setting-label">
              翻译
            </div>
            <a-select v-model:value="isTranslated" class="translate-select" :default-value="isTranslated.toString()">
              <a-select-option value="false">
                不翻译
              </a-select-option>
              <a-select-option value="true">
                翻译
              </a-select-option>
            </a-select>
          </div>
          <div class="setting-item">
            <div class="setting-label">
              区分发言人
            </div>
            <div class="button-group">
              <a-button :style="getButtonStyle('暂不体验', speakerType)" @click="speakerType = '暂不体验'">
                暂不体验
              </a-button>
              <a-button :style="getButtonStyle('单人演讲', speakerType)" @click="speakerType = '单人演讲'">
                单人演讲
              </a-button>
              <a-button :style="getButtonStyle('2人对话', speakerType)" @click="speakerType = '2人对话'">
                2人对话
              </a-button>
              <a-button :style="getButtonStyle('多人讨论', speakerType)" @click="speakerType = '多人讨论'">
                多人讨论
              </a-button>
            </div>
          </div>
          <div class="action-buttons">
            <a-button type="primary" class="start-button" @click="handleStart">
              开始转写
            </a-button>
            <a-button class="cancel-button" @click="props.onClose">
              取消
            </a-button>
          </div>
        </div>
      </div>
    </div>
  </a-modal>

  <!-- 上传中的模态框 -->
  <a-modal :open="isVisable" :footer="null" width="25rem" centered>
    <div class="uploading-progress">
      <a-spin />
      <p>文件上传中，请稍候...</p>
      <a-progress :percent="uploadProgress" status="active" />
    </div>
  </a-modal>
</template>

<style scoped lang="scss">
.modal-content {
  width: 100%;
  background: #fff;
  border-radius: 0.5rem;
  position: relative;
}

.modal-title {
  font-size: 1.5rem;
  text-align: left;
  margin-bottom: 1.25rem;
}

.modal-body {
  display: flex;
  padding: 0px 20px 20px;
}

.upload-dragger {
  background-color: #f6f5fd;
  border-radius: 0.5rem;
  padding: 0rem;
}

.upload-icon-wrapper {
  height: 6.25rem;
  width: 6.25rem;
  margin: 2.5rem auto -3.125rem;
}

.upload-icon {
  max-width: 100%;
  max-height: 100%;
}

.upload-text {
  font-size: 1rem;
  color: #605ce5;
  margin-top: 2.125rem;
}

.settings-section {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  gap: 1rem;
  padding-left: 0.625rem;
}

.setting-item {
  margin-bottom: 0.75rem;
}

.setting-label {
  font-size: 0.875rem;
  color: #333;
  margin-bottom: 0.625rem;
  display: flex;
  align-items: center;

  .info-icon {
    margin-left: 0.5rem;
  }
}

.button-group {
  display: flex;
  flex-wrap: wrap;
  gap: 0.25rem;
  margin-bottom: 0.5rem;
}

.translate-select {
  width: 100%;
}

.action-buttons {
  display: flex;
  gap: 0.625rem;

  .start-button {
    background-color: #6c63ff;
    border-color: #6c63ff;
    width: 6.25rem;
    border-radius: 0.938rem;

    &:hover {
      background-color: #5548c8;
      border-color: #5548c8;
    }
  }

  .cancel-button {
    width: 4.375rem;
    border-radius: 0.938rem;
    background-color: #f6f5fd;
    color: #605ce5;
    border-color: #605ce5;

    &:hover {
      background-color: #e6e5fc;
    }
  }
}

.uploading-progress {
  text-align: center;
  padding: 1.25rem;

  p {
    font-size: 1rem;
    margin-top: 1.25rem;
  }
}
</style>
